#!/usr/bin/env python
# coding: utf-8

# In[1]:


import requests
import json
import pandas as pd
import numpy as np 
from datetime import date
import datetime

# BCT 信息设置
user_info = {"userName":"zengjc","password":"Andyvic2021!"}
token_dict = {"日终报告": "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ6ZW5namMiLCJyb2xlcyI6WyLph5Hono3kuJrliqHliJvmlrDmgLvpg6gt6ZSA5ZSu5bKXIiwi6YeR6J6N5Lia5Yqh5Yib5paw5oC76YOoLeS6pOaYk-WylyJdLCJpc3MiOiJ0b25neXUudGVjaCIsImV4cCI6MTYzNDU0MDI3NjIyNSwiaWF0IjoxNjI2NzY0Mjc2MjI1LCJ1c2VybmFtZSI6InplbmdqYyJ9.BeR5X7ow4FaazY5zZq8JjYKmKgLlkjdJr0khYZpfDB4"
              ,"实时盈亏": "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ6ZW5namMiLCJyb2xlcyI6WyLph5Hono3kuJrliqHliJvmlrDmgLvpg6gt6ZSA5ZSu5bKXIiwi6YeR6J6N5Lia5Yqh5Yib5paw5oC76YOoLeS6pOaYk-WylyJdLCJpc3MiOiJ0b25neXUudGVjaCIsImV4cCI6MTYzNDcxNDUzNDYwOCwiaWF0IjoxNjI2OTM4NTM0NjA4LCJ1c2VybmFtZSI6InplbmdqYyJ9.eyyhJV38lotFM79Klq5OpmNTGfJIBJ5tOZ49NE7Ubys"
              ,"主体业务监测一":"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ6ZW5namMiLCJyb2xlcyI6WyLph5Hono3kuJrliqHliJvmlrDmgLvpg6gt6ZSA5ZSu5bKXIiwi6YeR6J6N5Lia5Yqh5Yib5paw5oC76YOoLeS6pOaYk-WylyJdLCJpc3MiOiJ0b25neXUudGVjaCIsImV4cCI6MTYzNDcxNDUzNDYwOCwiaWF0IjoxNjI2OTM4NTM0NjA4LCJ1c2VybmFtZSI6InplbmdqYyJ9.eyyhJV38lotFM79Klq5OpmNTGfJIBJ5tOZ49NE7Ubys"
              ,"主体业务监测二":"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ6ZW5namMiLCJyb2xlcyI6WyLph5Hono3kuJrliqHliJvmlrDmgLvpg6gt6ZSA5ZSu5bKXIiwi6YeR6J6N5Lia5Yqh5Yib5paw5oC76YOoLeS6pOaYk-WylyJdLCJpc3MiOiJ0b25neXUudGVjaCIsImV4cCI6MTYzNDcxNDUzNDYwOCwiaWF0IjoxNjI2OTM4NTM0NjA4LCJ1c2VybmFtZSI6InplbmdqYyJ9.eyyhJV38lotFM79Klq5OpmNTGfJIBJ5tOZ49NE7Ubys"
              }


#input:表格类型、用户信息、token; output: 表格Dataframe, 文件名
def get_form(form_type, user_info, token_dict, search_date):
    # 获得对应token
    if form_type == '日终报告':
        parameters = {"method":"rptPositionReportSearchPaged","params":{"page":0,"pageSize":1000,"reportName":"持仓明细_交易-日内-自然日","valuationDate":search_date,"orderBy":"effectiveDate","order":"desc"}}
    elif form_type == '实时盈亏':
        parameters = {"method":"rptIntradayMegaReportGet","params":{}}
    elif form_type == '主体业务监测一':
        parameters = {"method":"findCustomInstrumentReportByValuationDate","params":{"valuationDate":search_date}}
    elif form_type == '主体业务监测二':
        parameters = {"method":"findCustomTotalReportByValuationDate","params":{"valuationDate":search_date}}
    else:
        print('无'+ '"' + form_type + '"' + '表格类型\n')
        
    # 参数设置
    pay = user_info
    token = token_dict.get(form_type)
    headers = {"Authorization":"Bearer "+token}
    url = 'http://10.80.2.40/report-service/api/rpc'
    
    # 获得json 数据
    r=requests.post(url=url,json=parameters,headers = headers)
    data=r.json()#接口响应参数json化
    output_df, file_name = get_result_df(form_type, data, search_date)
    
    return output_df, file_name

# 得到对应表格
def get_result_df(form_type, data, search_date):
    output_df = pd.DataFrame()
    file_name = '空表格.xlsx'
    # 日终报告
    if form_type == '日终报告':
        result=data.get('result').get('page')
        
        if len(result)==0:
            print('搜索日期为:' +search_date +' 暂无日终报告\n')
            
        else:
            print('搜索日期为:' +search_date +' 日终报告中包含'+str(len(result))+'条交易记录\n')
            
            output_df = get_output_df(result)
            file_name = '持仓明细'+search_date[5:7]+search_date[8:10]+'.xlsx'
    
    # 实时盈亏
    elif form_type == '实时盈亏':
        result=data.get('result')
        output_df = get_output_df(result)
        
        # 报告生成时间
        time_created = str(output_df['createdAt'][0][:-7])
        print('实时风控报告生成时间为：'+time_created)
        print('实时风控报告包含条目数量为：'+str(len(result)) + '\n')
        time_name = time_created.replace(' ', '_').replace(':','-')
        file_name = '实时风控'+search_date[5:7]+search_date[8:10]+'.xlsx'
        
    # 主体业务监测一
    elif form_type == '主体业务监测一':
        result=data.get('result')
        
        if len(result)==0:
            print('搜索日期为:' +search_date +' 暂无主体业务监测报告一\n')
        else:
            print('搜索日期为:' +search_date +' 主体业务监测报告一中包含'+str(len(result))+'条交易记录\n')
            output_df = get_output_df(result)
            file_name = '主体业务监测报告一_'+search_date[5:7]+search_date[8:10]+'.xlsx'
        
    # 主体业务监测二
    elif form_type == '主体业务监测二':
        result=data.get('result')
        
        if len(result)==0:
            print('搜索日期为:' +search_date +' 暂无主体业务监测报告二\n')
        else:
            print('搜索日期为:' +search_date +' 主体业务监测报告二中包含'+str(len(result))+'条交易记录\n')
            output_df = get_output_df(result)
            file_name = '主体业务监测报告二_'+search_date[5:7]+search_date[8:10]+'.xlsx'
    
    # 表格输入错误
    else:
        print('无'+ '"' + form_type + '"' + '表格类型')
    
    return output_df, file_name 

# Json 转换成 pandas Dataframe 
def get_output_df(result):
    
    output_df=pd.DataFrame(result[0],index=[0])
    for i in range(len(result)-1):
        output_df_temp=pd.DataFrame(result[i+1],index=[0])
        output_df=pd.concat([output_df,output_df_temp])
    output_df=output_df.reset_index(drop=True)
    
    return output_df


###################################################################################
# 设置搜索数量
#today = date.today()
# 日期格式 2021-07-21，默认今天 
#search_date = str(today) 
#search_date = '2022-05-16'
search_date=str(datetime.date.today())

form_type_1 = "日终报告"
output_df_1, file_name_1 = get_form(form_type_1, user_info, token_dict, search_date)
output_df_1.to_excel(file_name_1)

form_type_2 = "实时盈亏"
output_df_2, file_name_2 = get_form(form_type_2, user_info, token_dict, search_date)
output_df_2.to_excel(file_name_2)

form_type_3 = "主体业务监测一"
output_df_3, file_name_3 = get_form(form_type_3, user_info, token_dict, search_date)
output_df_3.to_excel(file_name_3)

form_type_4 = "主体业务监测二"
output_df_4, file_name_4 = get_form(form_type_4, user_info, token_dict, search_date)
output_df_4.to_excel(file_name_4)
